package leetcode.editor.day;

// 1302. 层数最深叶子节点的和
// https://leetcode.cn/problems/deepest-leaves-sum/
class DeepestLeavesSum {
    public static void main(String[] args) {
        Solution solution = new DeepestLeavesSum().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        int sum = 0;
        int maxDeep = 0;

        public int deepestLeavesSum(TreeNode root) {
            dfs(root, 0);
            return sum;
        }

        public void dfs(TreeNode root, int deep) {
            if (root.left == null && root.right == null) {
                if (deep == maxDeep) {
                    sum += root.val;
                    return;
                } else if (deep > maxDeep) {
                    maxDeep = deep;
                    sum = root.val;
                }
            }

            if (root.left != null) dfs(root.left, deep + 1);
            if (root.right != null) dfs(root.right, deep + 1);
        }

        // bfs
        /*public int deepestLeavesSum(TreeNode root) {
            if (root == null) return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int sum = 0;
            while (!queue.isEmpty()) {
                int size = queue.size();
                int val = 0;
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    if (node.left == null && node.right == null) val += node.val;
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
                sum = val;
            }
            return sum;
        }*/
    }
//leetcode submit region end(Prohibit modification and deletion)

}
